package com.yuhao.hbasetest.controller;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.yuhao.hbasetest.entity.Demo;
import com.yuhao.hbasetest.service.DemoService;
import com.yuhao.hbasetest.util.BaseController;
import com.yuhao.hbasetest.util.ResultData;
import com.yuhao.hbasetest.util.ResultType;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 */
@RestController
@RequestMapping("/demo")
public class DemoController extends BaseController {

    @Autowired
    private DemoService demoService;

    @Autowired
    private RestTemplate restTemplate;

    @ApiOperation(value = "测试controller", notes = "")
    @GetMapping("/test")
    public String test() {
        return "test";
    }

    @ApiOperation(value = "测试服务调用", notes = "")
    @PostMapping("/returnString")
    public String test(@RequestParam String str) {
        return str;
    }

    /**
     * @Descripton: 保存
     */
    @ApiOperation(value = "保存数据接口", notes = "保存数据接口")
    @PostMapping("/save")
    public ResultData save(Demo demo) {
        try {
            demoService.save(demo);
            return setResponseEntity(ResultType.SUCCESS.getDescription(), ResultType.SUCCESS.getCode(), null, true);
        } catch (Exception e) {
            e.printStackTrace();
            return setResponseEntity(ResultType.SERVER_ERROR.getDescription(), ResultType.SERVER_ERROR.getCode(), null, false);
        }
    }

    /**
     * @Descripton: 根据id查询
     */
    @ApiOperation(value = "根据id查询数据接口", notes = "根据id查询数据接口")
    @GetMapping("/get/{id}")
    public ResultData getBean(@PathVariable String id) {
        try {
            List<Demo> apples = demoService.getById(new Demo(), id);
            return setResponseEntity(ResultType.SUCCESS.getDescription(), ResultType.SUCCESS.getCode(), ImmutableMap.of("date", apples), true);
        } catch (Exception e) {
            e.printStackTrace();
            return setResponseEntity(ResultType.SERVER_ERROR.getDescription(), ResultType.SERVER_ERROR.getCode(), null, false);
        }
    }

    @ApiOperation(value = "获取所有表名", notes = "获取所有表名")
    @GetMapping("/getAllTableName")
    public ResultData getAllTableName() {
        try {
            List<String> allTableName = demoService.getAllTableName();
            return setResponseEntity(ResultType.SUCCESS.getDescription(), ResultType.SUCCESS.getCode(), ImmutableMap.of("date", allTableName), true);
        } catch (Exception e) {
            e.printStackTrace();
            return setResponseEntity(ResultType.SERVER_ERROR.getDescription(), ResultType.SERVER_ERROR.getCode(), null, false);
        }
    }

    @ApiOperation(value = "根据表名获取列", notes = "根据表名获取列")
    @GetMapping("/getFamilies/{tableName}")
    public ResultData getFamilies(@PathVariable String tableName) {
        try {
            List<String> families = demoService.getFamilies(tableName);
            return setResponseEntity(ResultType.SUCCESS.getDescription(), ResultType.SUCCESS.getCode(), ImmutableMap.of("date", families), true);
        } catch (Exception e) {
            e.printStackTrace();
            return setResponseEntity(ResultType.SERVER_ERROR.getDescription(), ResultType.SERVER_ERROR.getCode(), null, false);
        }
    }


    @ApiOperation(value = "根据表名遍历数据", notes = "根据表名遍历数据")
    @GetMapping("/getResultScanner/{tableName}")
    public ResultData getResultScanner(@PathVariable String tableName) {
        try {
            Map<String, Map<String, String>> resultScanner = demoService.getResultScanner(tableName);
            return setResponseEntity(ResultType.SUCCESS.getDescription(), ResultType.SUCCESS.getCode(), ImmutableMap.of("date", resultScanner), true);
        } catch (Exception e) {
            e.printStackTrace();
            return setResponseEntity(ResultType.SERVER_ERROR.getDescription(), ResultType.SERVER_ERROR.getCode(), null, false);
        }
    }

    @ApiOperation(value = "调用hbase服务通过表名获取第一个rowkey", notes = "调用hbase服务通过表名获取第一个rowkey")
    @PostMapping("/restTemplateGetFirstRowkey")
    public ResultData restTemplateGetFirstRowkey() {
        String tableName = "BILL_ACCOUNTING_ELE_DETAIL";
        String url = "http://192.168.1.204:5529/hbaseServer/getFirstRowKey";
        HashMap<String, String> hashMap = Maps.newHashMap();
        hashMap.put("tableName", tableName);
        String url1 = concatUrl(url, hashMap);
        //HttpHeaders headers =  new HttpHeaders();
        //headers.setContentType(MediaType.APPLICATION_JSON);
        //headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //HttpEntity<String> stringHttpEntity = new HttpEntity<>(json.toString(), headers);
        try {
            String obj = restTemplate.postForObject(url1, null, String.class);
            return setResponseEntity(ResultType.SUCCESS.getDescription(), ResultType.SUCCESS.getCode(), ImmutableMap.of("date", obj), true);
        } catch (Exception e) {
            e.printStackTrace();
            return setResponseEntity(ResultType.SERVER_ERROR.getDescription(), ResultType.SERVER_ERROR.getCode(), null, false);
        }
    }

    private static <V> String concatUrl(String url, Map<String, V> map) {
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        Set<String> strings = map.keySet();
        for (String string : strings) {
            if (map.get(string) != null && !"".equals(map.get(string))) {
                sb.append(string).append("=").append(map.get(string)).append("&");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
